package com.zhy.sunmi.fragment.sell;

import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.greendao.gen.SellGoodHistoryDao;
import com.zhy.greendao.gen.SoldGoodDetailDao;
import com.zhy.sunmi.MyApplication;
import com.zhy.sunmi.PrintUtil4;
import com.zhy.sunmi.R;
import com.zhy.sunmi.bean.SellGoodHistory;
import com.zhy.sunmi.bean.SocketErrorBean;
import com.zhy.sunmi.bean.SocketLogBean;
import com.zhy.sunmi.bean.SocketSuccessBean;
import com.zhy.sunmi.bean.SoldGoodDetail;
import com.zhy.sunmi.myView.MyPresentation;
import com.zhy.sunmi.utils.ScreenUtils;
import com.zhy.sunmi.utils.XMathUtil;
import com.zhy.sunmi.utils.network.ProgressSubscriber;
import com.zhy.sunmi.utils.network.RetrofitUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.zhy.sunmi.MyApplication.pos_usb;
import static com.zhy.sunmi.fragment.sell.SubSellFragment.getSecondTimestamp;
import static com.zhy.sunmi.utils.PrintUtil.cutPaper;
import static com.zhy.sunmi.utils.PrintUtil.printBar;
import static com.zhy.sunmi.utils.PrintUtil.printText;


/**
 * @author zhouhongyang
 */
public class SubRefundPayFragment extends Fragment {
    private View rootView;
    private RecyclerView recyclerView_refund;
    private List<SoldGoodDetail> soldGoodDetails = new ArrayList<>();
    private TextView tv_total_money;
    private String url = MyApplication.getInstance().getUrl();
    private static String TAG = "Socket";
    private SellGoodHistoryDao sellGoodHistoryDao = MyApplication.getDaoSession().getSellGoodHistoryDao();
    private SoldGoodDetailDao soldGoodDetailDao = MyApplication.getDaoSession().getSoldGoodDetailDao();

    private TextView bt_return;
    private TextView tv_cash;
    private TextView tv_card;
    private TextView tv_alipay;
    private TextView tv_wechat;
    private TextView tv_discount;
    private TextView tv_totalvat;
    private TextView bt_finish;
    private TextView tv_totalmoney;
    private long id;
    private AlertDialog cardDialog;
    private AlertDialog dialogA;
    private SellGoodHistory sellGoodHistory;
    private MyPresentation myPresentation;
    private TextView tv_confirm_card;
    private TextView tv_cancel_card;
    TextView tv_msg;
    private  BigDecimal totalMoney=new BigDecimal(0);
    private int number;
    private String notes="";



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_sub_refund_pay, container, false);
            initView(rootView);

        } else {

        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }

        MyApplication.getInstance().setHandler(handler);
        return rootView;
    }

    private void initView(View rootView) {
        initBaseView(rootView);
        initRecyclerView();

    }

    public void hiddenButton(){
        tv_wechat.setVisibility(View.INVISIBLE);
        tv_alipay.setVisibility(View.INVISIBLE);
        tv_cash.setVisibility(View.INVISIBLE);
        tv_card.setVisibility(View.INVISIBLE);
    }
    public void showButton(){
//        tv_wechat.setVisibility(View.VISIBLE);
//        tv_alipay.setVisibility(View.VISIBLE);
        tv_cash.setVisibility(View.VISIBLE);
        tv_card.setVisibility(View.VISIBLE);
        bt_finish.setVisibility(View.INVISIBLE);
        bt_return.setVisibility(View.VISIBLE);
    }

    private void initBaseView(View view) {
        tv_total_money=rootView.findViewById(R.id.tv_total_money);
        bt_return = view.findViewById(R.id.bt_return);
        bt_finish = view.findViewById(R.id.bt_finish);
        bt_finish.setVisibility(View.INVISIBLE);
        tv_discount = view.findViewById(R.id.tv_discount);
        tv_totalvat = view.findViewById(R.id.tv_vat);
        tv_totalmoney = view.findViewById(R.id.tv_total_money);
        tv_cash = view.findViewById(R.id.tv_cash);
        tv_alipay = view.findViewById(R.id.tv_alipay);
        tv_wechat = view.findViewById(R.id.tv_wechat);
        tv_cash.setOnClickListener(v -> {
            MyApplication.getInstance().openCashDrawer();
            Date date = new Date();
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-" + MyApplication.MachineId + "-HHmmss");
            SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
//            String str = dateFormat.format(date);
            String str2 = dateFormat2.format(date);
            long paytime=getSecondTimestamp(date);
            List<SellGoodHistory> sellGoodHistories2 = sellGoodHistoryDao.queryBuilder().where(SellGoodHistoryDao.Properties.Id.eq(soldGoodDetails.get(0).getSellGoodHistoryId())).list();
            String code=sellGoodHistories2.get(0).getOrderCode();
            saveSellHistory(code,totalMoney+"", "0.00",4,paytime,1,"退款成功");
            print(code,str2,totalMoney+"", "0.00","Cash");
            bt_finish.setVisibility(View.VISIBLE);
            bt_return.setVisibility(View.INVISIBLE);
            hiddenButton();
        });

        tv_card = view.findViewById(R.id.tv_card);
        bt_return.setOnClickListener(v -> {
            SubSellingFragment subSellingFragment = (SubSellingFragment) getParentFragment();
            subSellingFragment.goShopping(0, null, null);

        });

        bt_finish.setOnClickListener(v -> {
            SubSellingFragment subSellingFragment = (SubSellingFragment) getParentFragment();
            subSellingFragment.goShopping(0, null, "return");
            bt_finish.setVisibility(View.INVISIBLE);
            showButton();
        });


        tv_card.setOnClickListener(v -> {
//            String a=sellGoodHistory.getTotalMoneyAfterDiscount();
            BigDecimal  aa= XMathUtil.multiply(totalMoney,new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN);;
            String tid=MyApplication.getInstance().getTid();
            id=System.currentTimeMillis();
            String str = "{ \"jsonrpc\": \"2.0\", \"method\": \"refund\", \"params\": { \"tid\": \""+tid+"\", \"currency\": \"GBP\", \"amount\":"+aa+" },\"id\":"+id+" }";
//            if(MyApplication.getInstance().getWebSocketClient().isOpen()){
//                MyApplication.getInstance().getWebSocketClient().send(str);
                showDialog3();
//            }else {
////                Toast.makeText(getContext(),"error",Toast.LENGTH_SHORT).show();
//                MyApplication.getInstance().initCardPay();
//                showDialogError();
//            }
        });

    }

    private void initRecyclerView() {
        recyclerView_refund = rootView.findViewById(R.id.recyclerView);
        recyclerView_refund.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView_refund.setAdapter(new CommonAdapter<SoldGoodDetail>(getContext(), R.layout.item_selling_good, soldGoodDetails) {
            @Override
            protected void convert(ViewHolder holder, SoldGoodDetail soldGoodDetail, int position) {
                holder.setText(R.id.selling_number, soldGoodDetail.getNumber() + "");
                double b = soldGoodDetail.getPrice();
                BigDecimal p = BigDecimal.valueOf(b);
                String t_price = XMathUtil.multiply(soldGoodDetail.getNumber(), soldGoodDetail.getPrice()).setScale(2, BigDecimal.ROUND_DOWN).toString();
                holder.setText(R.id.tv_selling_money, "£" + t_price);
                holder.setText(R.id.tv_goodname, soldGoodDetail.getEnglishName());
                holder.setText(R.id.tv_goodCname, soldGoodDetail.getChineseName());
                holder.setText(R.id.tv_good_disoff, new Double(soldGoodDetail.getDiscount()).intValue() + "%");
                holder.setVisible(R.id.iv_ljt,false);
            }
        });
    }


    public void go(List<SoldGoodDetail> soldGoodDetails,String notes) {
        if (soldGoodDetails != null) {
            this.soldGoodDetails.clear();
            this.soldGoodDetails.addAll(soldGoodDetails);
            this.notes=notes;
            recyclerView_refund.getAdapter().notifyDataSetChanged();
            setRefundText();
        }
    }

    private void setRefundText() {
        int number = 0;
        BigDecimal totalmoney = new BigDecimal(0);

        for (SoldGoodDetail soldGoodDetail : soldGoodDetails) {
            number += soldGoodDetail.getNumber();
            BigDecimal t_price = XMathUtil.multiply(soldGoodDetail.getNumber(), soldGoodDetail.getPriceAfterDis()).setScale(2, BigDecimal.ROUND_DOWN);
            totalmoney = XMathUtil.add(totalmoney, t_price);
        }
        this.number=number;
        tv_total_money.setText("£" + totalmoney);
        totalMoney=totalmoney;
    }

    private void showDialog3() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_pay_card_waiting, null, false);
        cardDialog = new AlertDialog.Builder(getContext()).setView(view).create();
        cardDialog.setCanceledOnTouchOutside(false);
        cardDialog.show();
        cardDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

        tv_confirm_card = view.findViewById(R.id.tv_confirm);
        tv_cancel_card = view.findViewById(R.id.tv_cancel);
//        tv_confirm_card.setVisibility(View.VISIBLE);
        tv_msg = view.findViewById(R.id.tv_change);

        tv_msg.setText("Sorry response from Car Machine is time Out!");
        tv_confirm_card.setText("Manual Confirm");
        tv_cancel_card.setText("Manual Cancel");
        tv_confirm_card.setVisibility(View.VISIBLE);
        tv_cancel_card.setVisibility(View.VISIBLE);
        tv_confirm_card.setOnClickListener(v -> {
            showDialog4("Are you sure to Manual Confirm?",1);
        });
        tv_cancel_card.setOnClickListener(v -> {
            showDialog4("Are you sure Manual Cancel?",2);
        });


    }

    private void showDialogError() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_error, null, false);
        Dialog timeoutDialog = new AlertDialog.Builder(getContext()).setView(view).create();
        timeoutDialog.setCanceledOnTouchOutside(false);
        timeoutDialog.show();
        timeoutDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView tv_confirm_card = view.findViewById(R.id.tv_confirm);
        TextView tv_cancel_card = view.findViewById(R.id.tv_cancel);
//        tv_confirm_card.setVisibility(View.VISIBLE);
        TextView tv_msg = view.findViewById(R.id.tv_change);





        tv_cancel_card.setOnClickListener(v -> {

            timeoutDialog.dismiss();


        });

        tv_confirm_card.setOnClickListener(v -> {

            timeoutDialog.dismiss();
            showDialog7();

        });





    }
    private void showDialog7() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_pay_card_waiting, null, false);
        Dialog cardDialog = new AlertDialog.Builder(getContext()).setView(view).create();
        cardDialog.setCanceledOnTouchOutside(false);
        cardDialog.show();
        cardDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);
        TextView tv_confirm_card = view.findViewById(R.id.tv_confirm);
        TextView tv_cancel_card = view.findViewById(R.id.tv_cancel);
//        tv_confirm_card.setVisibility(View.VISIBLE);
        TextView tv_msg = view.findViewById(R.id.tv_change);
        tv_msg.setText("Please switch to Manually Mode!");
        tv_confirm_card.setText("Manual Confirm");
        tv_cancel_card.setText("Manual Cancel");
        tv_confirm_card.setVisibility(View.VISIBLE);
        tv_cancel_card.setVisibility(View.VISIBLE);
        tv_confirm_card.setOnClickListener(v2 -> {
            showDialog8("Are you sure to Manual Confirm?",1,cardDialog);
        });
        tv_cancel_card.setOnClickListener(v2 -> {
            showDialog8("Are you sure Manual Cancel?",2,cardDialog);
        });


    }




    private void showDialog8(String str,int f,Dialog dialog) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_pay_card_timeout, null, false);
        Dialog timeoutDialog = new AlertDialog.Builder(getContext()).setView(view).create();
        timeoutDialog.setCanceledOnTouchOutside(false);
        timeoutDialog.show();
        timeoutDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView tv_confirm_card = view.findViewById(R.id.tv_confirm);
        TextView tv_cancel_card = view.findViewById(R.id.tv_cancel);
//        tv_confirm_card.setVisibility(View.VISIBLE);
        TextView tv_msg = view.findViewById(R.id.tv_change);

        tv_msg.setText(str);




        tv_cancel_card.setOnClickListener(v -> {
            if(f==1){
                timeoutDialog.dismiss();
                dialog.dismiss();
            }else if(f==2){
                timeoutDialog.dismiss();
                dialog.dismiss();
            }
        });

        tv_confirm_card.setOnClickListener(v -> {
            if(f==1){
                printCard("手动确认");
                timeoutDialog.dismiss();
                dialog.dismiss();
                if(cardDialog!=null){

                    cardDialog.dismiss();
                }

            }else if(f==2){
                timeoutDialog.dismiss();
                dialog.dismiss();
                if(cardDialog!=null){

                    cardDialog.dismiss();
                }
//                cardDialog.dismiss();
            }

        });

    }

    private void printCard(String result) {
        Date date = new Date();
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-" + MyApplication.MachineId + "-HHmmss");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

//        String str = dateFormat.format(date);
        List<SellGoodHistory> sellGoodHistories2 = sellGoodHistoryDao.queryBuilder().where(SellGoodHistoryDao.Properties.Id.eq(soldGoodDetails.get(0).getSellGoodHistoryId())).list();
        String code=sellGoodHistories2.get(0).getOrderCode();
        String str2 = dateFormat2.format(date);
        long paytime=getSecondTimestamp(date);
        saveSellHistory(code,totalMoney+"", "0.00",4,paytime,2,result);
        print(code,str2,totalMoney+"", "0.00","Card");
        bt_finish.setVisibility(View.VISIBLE);
        bt_return.setVisibility(View.INVISIBLE);
        hiddenButton();
        //状态0 方式1


    }


    private void saveSellHistory(String orderCode,String actualPayMoney,String changeMoney,int payStatus,long payTime,int paymentMethod,String result ) {
//        List<SellGoodHistory> sellGoodHistories2 = sellGoodHistoryDao.queryBuilder().where(SellGoodHistoryDao.Properties.Id.eq(soldGoodDetails.get(0).getSellGoodHistoryId())).list();
//        String code=sellGoodHistories2.get(0).getOrderCode();
        SellGoodHistory sellGoodHistory = new SellGoodHistory();
        sellGoodHistory.setId(null);
        sellGoodHistory.setOrderCode(orderCode);
        sellGoodHistory.setCashierId(MyApplication.UserId);
        sellGoodHistory.setCashRegisterId(MyApplication.MachineId);
        sellGoodHistory.setTotalNumber(number);
        sellGoodHistory.setCustomerCode("");
        sellGoodHistory.setRemarks(notes);
//        sellGoodHistory.setPaymentMethod(0);
        sellGoodHistory.setTotalMoney(totalMoney+"");
        sellGoodHistory.setTotalMoneyAfterDiscount("0");
        sellGoodHistory.setTotalVat("0");
        sellGoodHistory.setTotalSave("0");
//        sellGoodHistory.setPayStatus(4);
        sellGoodHistory.setPayTime(getSecondTimestamp(new Date()));
//        sellGoodHistory.setChangeMoney("0");
//        sellGoodHistory.setActualPayMoney("0");
        sellGoodHistory.setDiscountOffCode("");
        sellGoodHistory.setDicountRemCode("");
        sellGoodHistory.setSoldGoodDetailList(soldGoodDetails);

//        sellGoodHistory.setOrderCode(orderCode);
        sellGoodHistory.setActualPayMoney(actualPayMoney);
        sellGoodHistory.setChangeMoney(changeMoney);
        sellGoodHistory.setPayStatus(payStatus);
        sellGoodHistory.setPayTime(payTime);
        sellGoodHistory.setPaymentMethod(paymentMethod);
        sellGoodHistory.setPayResult(result);

        Long id = sellGoodHistoryDao.insert(sellGoodHistory);
//        List<SoldGoodDetail> soldGoodDetails = sellGoodHistory.getSoldGoodDetailList();
        for (SoldGoodDetail soldGoodDetail : soldGoodDetails) {
            soldGoodDetail.setId(null);
            BigDecimal t_price1 = XMathUtil.multiply(soldGoodDetail.getNumber(), soldGoodDetail.getPrice()).setScale(2, BigDecimal.ROUND_DOWN);
            BigDecimal t_price2 = XMathUtil.multiply(soldGoodDetail.getNumber(), soldGoodDetail.getPriceAfterDis()).setScale(2, BigDecimal.ROUND_DOWN);
            soldGoodDetail.setTotalPrice(t_price1.doubleValue());
            soldGoodDetail.setTotalPriceAfterDis(t_price2.doubleValue());
            soldGoodDetail.setSellGoodHistoryId(id);
        }
        soldGoodDetailDao.insertInTx(soldGoodDetails);



        List<SellGoodHistory> sellGoodHistories2 = sellGoodHistoryDao.queryBuilder().where(SellGoodHistoryDao.Properties.PortSuccess.eq(false)).list();



        for(SellGoodHistory sellGoodHistory2:sellGoodHistories2){
            sellGoodHistory2.getSoldGoodDetails();
            getCoupons2(MyApplication.api_token,sellGoodHistory2);
        }



    }


    void getCoupons2(String api_token,SellGoodHistory sellGoodHistory2) {
        Gson gson = new Gson();
        String as = gson.toJson(sellGoodHistory2);
        RetrofitUtil.getInstance().getCoupons2(new ProgressSubscriber<>(a -> {

            sellGoodHistory2.setPortSuccess(true);
            sellGoodHistoryDao.update(sellGoodHistory2);

        }, getActivity()), api_token, as);
    }


    private void print(String orderCode,String time,String giveCash, String changestr,String payMethod) {
        if (pos_usb == null) {
            Toast.makeText(MyApplication.getInstance().getApplicationContext(), "Please connect the printer", Toast.LENGTH_LONG).show();
            return;
        }
        String a = PrintUtil4.printxx(soldGoodDetails);
//            System.out.print(a);

        printText("------------Refund-----------", 1, 1, 20);

        printText("Golden Mayfair Chinese Restaurant", 1, 1, 20);
        printText("3 West Road", 1, 0, 20);
        printText("Westcliff-on-Sea, Essex,SS0 9AU", 1, 0, 20);
        printText("Telephone 01702352707", 1, 0, 20);

        printText("", 0, 0);
        printText("Order Ref: " + orderCode, 0, 1);
        printText("------------------------------------------", 0, 0);
//            printText("Description                          Total", 0, 0);
//            printText("------------------------------------------", 0, 0);
        printText(a, 0, 0);
        printText("Total                                " + totalMoney, 0, 0);
//        printText("------------------------------------------", 0, 0);
//        printText("YOU SAVED  " + sellGoodHistory.getTotalSave(), 1, 1, 10);
//        printText("------------------------------------------", 0, 0);
//        printText("Grand Total                          " + sellGoodHistory.getTotalMoneyAfterDiscount(), 0, 1);
//        printText("------------------------------------------", 0, 0);
//        printText("Number Of Items                        " + sellGoodHistory.getTotalNumber() + "\n", 0, 1);
//        printText("VAT Summary Breakdown", 1, 3, 30);
//        printText("Total      VAT Value", 1, 1, 20);
//        printText(sellGoodHistory.getTotalMoneyAfterDiscount() + "         " + sellGoodHistory.getTotalVat(), 1, 0, 20);
//        printText("Payment Details\n", 0, 3);
////        printText("Paid By Cash                         " + giveCash, 0, 1, 20);
//        printText("Paid By "+payMethod+"                         " + giveCash, 0, 1, 20);
//        printText("Change                               " + changestr, 0, 1, 20);
        printText("You have been Served By" + MyApplication.UserName, 1, 0, 20);
        printText("Till No:" + "Till"+MyApplication.getInstance().getMachineId(), 0, 1, 10);
        printText("", 1, 1, 10);
        printBar(orderCode);
        printText(time, 1, 1, 20);
        printText("Please Keep for your records", 1, 0, 20);
        printText("Published Terms and Conditions Apply", 1, 0, 20);
        cutPaper();

        List<SoldGoodDetail> hotGoods=new ArrayList<>();

//        for(SoldGoodDetail hotGood :soldGoodDetailList){
//            if(hotGood.getHot_goods().equals("true")){
//                hotGoods.add(hotGood);
//            }else {
//
//            }
//
//        }
        if(hotGoods.size()!=0){
            printText(PrintUtil4.printxx(hotGoods), 0, 0);
            cutPaper();
        }

    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            Gson gson = new Gson();
            Log.d("socket", msg.obj.toString());

            try {
                JSONObject jsonObject=new JSONObject(msg.obj.toString());
                if(jsonObject.has("method")){
                    SocketLogBean socketLogBean = gson.fromJson(msg.obj.toString(), SocketLogBean.class);
                    if(socketLogBean.getMethod().equals("signatureVerificationRequest")){
                        tv_msg.setText("Please Waiting");
                        long id=socketLogBean.getId();
                        showDialog5("Please check the Signature of the card!",id);
                    }else {
                        tv_msg.setText(socketLogBean.getParams().getNotificationValue());
                    }

                }else if(jsonObject.has("result")){
                    SocketSuccessBean socketSuccessBean = gson.fromJson(msg.obj.toString(), SocketSuccessBean.class);
                    String m=socketSuccessBean.getResult().getTransactionResult();
                    tv_msg.setText(socketSuccessBean.getResult().getTransactionResult());


                    if(m.equals("TIMED_OUT")){
                        tv_msg.setText("Sorry response from Car Machine is time Out!");
                        tv_confirm_card.setText("Manual Confirm");
                        tv_cancel_card.setText("Manual Cancel");
                        tv_confirm_card.setVisibility(View.VISIBLE);
                        tv_cancel_card.setVisibility(View.VISIBLE);
                        tv_confirm_card.setOnClickListener(v -> {
                            showDialog4("Are you sure to Manual Confirm?",1);
                        });
                        tv_cancel_card.setOnClickListener(v -> {
                            showDialog4("Are you sure Manual Cancel?",2);
                        });

                    }else if(m.equals("SUCCESSFUL")){
                        tv_confirm_card.setVisibility(View.VISIBLE);
                        tv_cancel_card.setVisibility(View.INVISIBLE);
                        String cardresult=msg.obj.toString();
                        tv_confirm_card.setOnClickListener(v -> {
                            cardDialog.dismiss();
                            printCard(cardresult);
                        });


                    }else if(m.equals("UNSUCCESSFUL")){
                        tv_confirm_card.setVisibility(View.VISIBLE);
                        tv_cancel_card.setVisibility(View.VISIBLE);
                        tv_confirm_card.setOnClickListener(v -> {
                            cardDialog.dismiss();
//                            printCard()
                        });
                        tv_cancel_card.setOnClickListener(v -> {
                            cardDialog.dismiss();
                        });
                    }else {
                        tv_confirm_card.setVisibility(View.VISIBLE);
                        tv_cancel_card.setVisibility(View.VISIBLE);
                        tv_confirm_card.setOnClickListener(v -> {
                            cardDialog.dismiss();
//                            printCard()
                        });
                        tv_cancel_card.setOnClickListener(v -> {
                            cardDialog.dismiss();
                        });
                    }









                }else if(jsonObject.has("error")) {
                    SocketErrorBean socketErrorBean = gson.fromJson(msg.obj.toString(), SocketErrorBean.class);
                    tv_msg.setText("Card Machine Error:"+socketErrorBean.getError().getMessage());
                    tv_confirm_card.setVisibility(View.VISIBLE);
                    tv_confirm_card.setText("Manual Confirm");
                    tv_cancel_card.setVisibility(View.INVISIBLE);
                    tv_confirm_card.setOnClickListener(v -> {
//                        cardDialog.dismiss();

                        tv_msg.setText("Please switch to Manually Mode!");
                        tv_confirm_card.setText("Manual Confirm");
                        tv_cancel_card.setText("Manual Cancel");
                        tv_confirm_card.setVisibility(View.VISIBLE);
                        tv_cancel_card.setVisibility(View.VISIBLE);
                        tv_confirm_card.setOnClickListener(v2 -> {
                            showDialog4("Are you sure to Manual Confirm?",1);
                        });
                        tv_cancel_card.setOnClickListener(v2 -> {
                            showDialog4("Are you sure Manual Cancel?",2);
                        });




                    });
                    tv_cancel_card.setOnClickListener(v -> {
                        cardDialog.dismiss();
                    });
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return true;
        }
    });


    private void showDialog4(String str,int f) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_pay_card_timeout, null, false);
        Dialog timeoutDialog = new AlertDialog.Builder(getContext()).setView(view).create();
        timeoutDialog.setCanceledOnTouchOutside(false);
        timeoutDialog.show();
        timeoutDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView tv_confirm_card = view.findViewById(R.id.tv_confirm);
        TextView tv_cancel_card = view.findViewById(R.id.tv_cancel);
//        tv_confirm_card.setVisibility(View.VISIBLE);
        TextView tv_msg = view.findViewById(R.id.tv_change);

        tv_msg.setText(str);




        tv_cancel_card.setOnClickListener(v -> {
            if(f==1){
                timeoutDialog.dismiss();
            }else if(f==2){
                timeoutDialog.dismiss();
            }else {
                String str22 = "{ \"jsonrpc\": \"2.0\", \"id\": "+id+", \"result\": { \"accepted\": false } }";
                if(MyApplication.getInstance().getWebSocketClient().isOpen()){
                    MyApplication.getInstance().getWebSocketClient().send(str22);
                    timeoutDialog.dismiss();
                }
            }

        });

        tv_confirm_card.setOnClickListener(v -> {
            if(f==1){
                printCard("手动确认");
                timeoutDialog.dismiss();
                if(cardDialog!=null){
                    cardDialog.dismiss();
                }

            }else if(f==2){
                timeoutDialog.dismiss();
                if(cardDialog!=null){
                    cardDialog.dismiss();
                }
//                cardDialog.dismiss();
            }else {
//                String str22 = "{ \"jsonrpc\": \"2.0\", \"id\": 0, \"result\": { \"accepted\": true } }";
                String str22 = "{ \"jsonrpc\": \"2.0\", \"id\": "+id+", \"result\": { \"accepted\": true } }";
                if(MyApplication.getInstance().getWebSocketClient().isOpen()){
                    MyApplication.getInstance().getWebSocketClient().send(str22);
                    timeoutDialog.dismiss();
                }
            }

        });

    }


    private void showDialog5(String str,long id) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_pay_card_timeout, null, false);
        Dialog timeoutDialog = new AlertDialog.Builder(getContext()).setView(view).create();
        timeoutDialog.setCanceledOnTouchOutside(false);
        timeoutDialog.show();


        final Timer t = new Timer();
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                timeoutDialog.dismiss();
                //结束本界面并跳转到收派员列表的界面
                t.cancel();
            }
        }, 60000);






        timeoutDialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView tv_confirm_card = view.findViewById(R.id.tv_confirm);
        TextView tv_cancel_card = view.findViewById(R.id.tv_cancel);
//        tv_confirm_card.setVisibility(View.VISIBLE);
        TextView tv_msg = view.findViewById(R.id.tv_change);

        tv_msg.setText(str);





        tv_cancel_card.setOnClickListener(v -> {
            t.cancel();
            String str22 = "{ \"jsonrpc\": \"2.0\", \"id\": "+id+", \"result\": { \"accepted\": false } }";
            if(MyApplication.getInstance().getWebSocketClient().isOpen()){
                MyApplication.getInstance().getWebSocketClient().send(str22);
                timeoutDialog.dismiss();}


        });

        tv_confirm_card.setOnClickListener(v -> {
            t.cancel();
//                String str22 = "{ \"jsonrpc\": \"2.0\", \"id\": 0, \"result\": { \"accepted\": true } }";
            String str22 = "{ \"jsonrpc\": \"2.0\", \"id\": "+id+", \"result\": { \"accepted\": true } }";
            if(MyApplication.getInstance().getWebSocketClient().isOpen()){
                MyApplication.getInstance().getWebSocketClient().send(str22);
                timeoutDialog.dismiss();
            }


        });

    }

}